package com.lushixiang.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
@Component
public class TokenUtil{

    private final static String secretKey = "lushixiang";
    /**
     * 生成token
     */
    public static String generateToken(String user, int seconds) {
        log.info("用户{}获取token",user);
        Date start = new Date();
        long currentTime = System.currentTimeMillis() + seconds* 1000L;//一小时有效时间
        Date end = new Date(currentTime);
        return JWT.create()
                .withAudience(user)
                .withIssuedAt(start)
                .withExpiresAt(end)
                .sign(Algorithm.HMAC256(secretKey));
    }


    /**
     *
     * @return userId
     * 获取制定token中某个属性值
     */
    public static String getTokenValue(String token, String key) {
        log.info("获取token中的{}",key);
        try{
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secretKey)).build();
            jwtVerifier.verify(token).getAudience();
            return jwtVerifier.verify(token).getClaim(key).asString();
        }catch (Exception e){
            log.info("获取key的过程发生异常：{}",e.toString());
            return null;
        }
    }

    public static String getTokenAudience(String token) {
        log.info("获取token中的Audience");
        try{
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secretKey)).build();
            jwtVerifier.verify(token).getAudience();
            return jwtVerifier.verify(token).getAudience().get(0);
        }catch (Exception e){
            log.info("获取Audience的过程发生异常：{}",e.toString());
            return null;
        }
    }

    // 验证token是否正确
    public static boolean verifyToken(String token){
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secretKey)).build();
            verifier.verify(token);
            log.info("严重token：{} 成功",token);
            return true;
        }catch (Exception e){
            log.info("token: {} 判断失败",e.toString());
            return  false;
        }
    }
}
